package com.dly.hope.dao;

import com.dly.hope.dto.UserSocketDto;
import com.dly.hope.model.vo.UserShow;
import com.dly.hope.modle.QAccountRole;
import com.dly.hope.modle.QRole;
import com.dly.hope.modle.QUserAccount;
import com.dly.hope.modle.UserAccount;
import com.dly.hope.pageUtils.PageRo;
import com.dly.hope.pageUtils.Page;
import com.dly.hope.type.RoleType;
import com.querydsl.core.types.Projections;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author linyu.dai
 * @project myserve
 * @description 用户账号Dao
 * @creat 2022/8/26 14:02:34
 */
@Repository
public class UserAccountDao extends BaseDao {

    private QUserAccount basePath() {
        return QUserAccount.userAccount;
    }

    public List<UserAccount> findAll() {
        return queryFactory.selectFrom(basePath()).fetch();
    }

    public List<UserSocketDto> findUser(List<String> userIds) {
        return queryFactory.select(Projections.bean(
                        UserSocketDto.class,
                        basePath().id.as("userId"),
                        basePath().accountName.as("name")
                )).from(basePath())
                .where(basePath().id.in(userIds).and(efficient(basePath().dataStatus)))
                .fetch();
    }

    public Page<UserShow> getAll(PageRo pageRo){
        Page<UserShow> userShowPage = new Page<>(pageRo);
        List<UserShow> fetch = queryFactory.select(Projections.bean(
                        UserShow.class,
                        basePath().id,
                        basePath().accountName.as("name"),
                        basePath().accountNumber.as("account"),
                        basePath().email,
                        basePath().avatar,
                        basePath().createDate,
                        basePath().dataStatus.as("status")
                )).from(basePath())
                .limit(pageRo.getPageSize())
                .offset((long) pageRo.getPageSize() * (pageRo.getPageNumber() - 1))
                .orderBy(basePath().createDate.desc())
                .fetch();
        userShowPage.setContent(fetch);
        return userShowPage;
    }

    public List<UserAccount> getSuperAccount(RoleType roleType){

        QAccountRole accountRole = QAccountRole.accountRole;

        QRole role = QRole.role;

        return queryFactory
                .selectFrom(basePath())
                .leftJoin(accountRole).on(basePath().id.eq(accountRole.accountId))
                .leftJoin(role).on(accountRole.roleId.eq(role.id))
                .where(role.roleType.eq(roleType).and(basePath().dataStatus.eq(1)))
                .fetch();
    }

}
